# coding=utf-8
import uuid

from sutras import enums, models


def get_or_create_user(open_id):
    user, created = models.CustomUser.objects.get_or_create(
        open_id=open_id,
        defaults={
            "uid": uuid.uuid1().hex,
        })
    if created:
        models.UserLevelInfo.objects.create(user=user)
    return user


def get_user_info(user):
    """
    获取个人信息
    """
    info_data = {
        "progress": None,
        "address": None,
    }

    total_count = models.UserLevelInfo.objects.count()
    level_info = models.UserLevelInfo.objects.filter(user=user).first()
    if level_info:

        queryset = models.UserLevelInfo.objects.all()
        finish_char_less_count = queryset.filter(
            finish_char_num__lt=level_info.finish_char_num).count()
        finish_book_less_count = queryset.filter(
            finish_book_num__lt=level_info.finish_book_num).count()
        print_book_less_count = queryset.filter(
            print_book_num__lt=level_info.print_book_num).count()

        info_data["progress"] = {
            "online_time": {
                "num": level_info.total_time,
                "rank": "80%",
            },
            "copy_chars": {
                "num": level_info.finish_char_num,
                "rank": "{0}%".format(
                    round(finish_char_less_count / total_count * 100)),
            },
            "copy_books": {
                "num": level_info.finish_book_num,
                "rank": "{0}%".format(
                    round(finish_book_less_count / total_count * 100)),
            },
            "print_books": {
                "num": level_info.print_book_num,
                "rank": "{0}%".format(
                    round(print_book_less_count / total_count * 100)),
            },
            "assist_copy_pages": {
                "num": level_info.assist_page_num,
                "rank": "80%",
            }
        }

    default_address = models.UserAddress.objects.filter(
        user=user, type=enums.UserAddressType.default,
        status=enums.UserAddressStatus.normal).first()
    if default_address:
        info_data["address"] = {
            "contact": default_address.contact,
            "phone": default_address.phone,
            "address": default_address.address,
        }
    return info_data


def get_user_address_list(user):
    """
    获取用户地址列表
    """
    address_objs = models.UserAddress.objects.filter(
        user=user, status=enums.UserAddressStatus.normal)
    address_list = []
    for address_obj in address_objs:
        address_list.append({
            "id": address_obj.id,
            "address": address_obj.address,
            "contact": address_obj.contact,
            "phone": address_obj.phone,
            "is_default": address_obj.type == enums.UserAddressType.default,
        })
    return address_list


def create_user_address(user, address, contact, phone):
    if models.UserAddress.objects.filter(
            user=user, status=enums.UserAddressStatus.normal,
            type=enums.UserAddressType.default):
        # 已有默认地址，则新增的地址非默认
        _type = enums.UserAddressType.not_default
    else:
        _type = enums.UserAddressType.default
    models.UserAddress.objects.create(
        user=user, contact=contact, phone=phone, address=address, type=_type)


def update_default_address(user, address_id):
    models.UserAddress.objects.filter(
        user=user, status=enums.UserAddressStatus.normal).update(
            type=enums.UserAddressType.not_default)
    models.UserAddress.objects.filter(id=address_id, user=user).update(
        type=enums.UserAddressType.default)


def delete_user_address(user, address_id):
    models.UserAddress.objects.filter(id=address_id, user=user).update(
        status=enums.UserAddressStatus.deleted)


def star_sutra_edition(user, sutra_edition_id):
    sutra_edition = models.SutraEdition.objects.filter(
        id=sutra_edition_id).first()
    if sutra_edition:
        models.UserFavorite.objects.update_or_create(
            user=user, sutra_edition=sutra_edition,
            defaults={"status": enums.UserFavoriteStatus.normal})


def unstar_sutra_edition(user, sutra_edition_id):
    sutra_edition = models.SutraEdition.objects.filter(
        id=sutra_edition_id).first()
    if sutra_edition:
        models.UserFavorite.objects.update_or_create(
            user=user, sutra_edition=sutra_edition,
            defaults={"status": enums.UserFavoriteStatus.deleted})


def get_starred_sutra_edition_list(user, limit, offset):
    sutra_edition_ids = models.UserFavorite.objects.filter(
        user=user,
        status=enums.UserFavoriteStatus.normal
    )[offset:offset+limit].values_list(
            "sutra_edition_id", flat=True)
    sutra_edition_ids = list(sutra_edition_ids)
    sutra_edition_objs = models.SutraEdition.objects.filter(
        id__in=sutra_edition_ids)

    data_list = []
    for sutra_edition_obj in sutra_edition_objs:

        if models.UserTranscription.objects.filter(
                user=user, sutra_edition=sutra_edition_obj,
                status=enums.UserTranscription.finished):
            has_finished = True
        else:
            has_finished = False

        data = {
            "id": sutra_edition_obj.id,
            "name": sutra_edition_obj.name,
            "cover_url": sutra_edition_obj.cover_url,
            "has_finished": has_finished,
        }
        data_list.append(data)

    return data_list
